package org.aurora.client.processor;

import org.aurora.client.ITaskProcessor;
import org.aurora.model.request.ExecuteTaskRequest;
import org.aurora.model.response.CommonResponse;
import org.aurora.remote.AbstractRemoteProcessor;

import java.util.Map;
import java.util.concurrent.*;

public class ExecuteTaskProcessor extends AbstractRemoteProcessor<ExecuteTaskRequest, CommonResponse> {

    private int coreThreadPoolSize;

    private int maxThreadPoolSize;

    private Map<String, ITaskProcessor> taskProcessorMap;

    private ExecutorService workExecutorService;

    public ExecuteTaskProcessor(int coreThreadPoolSize, int maxThreadPoolSize, Map<String, ITaskProcessor> taskProcessorMap) {
        this.coreThreadPoolSize = coreThreadPoolSize;
        this.maxThreadPoolSize = maxThreadPoolSize;
        this.taskProcessorMap = taskProcessorMap;
        // todo 线程池的各个参数该如何设置
        this.workExecutorService = new ThreadPoolExecutor(coreThreadPoolSize, maxThreadPoolSize, 1000l, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
    }

    @Override
    public CommonResponse doProcessor(ExecuteTaskRequest request) {
        String taskName = request.getTaskName();

        this.workExecutorService.execute(() -> {
            try {
                ITaskProcessor taskProcessor = this.taskProcessorMap.get(taskName);
                taskProcessor.processor(request.getContext());
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });

        return CommonResponse.buildSuccess();
    }
}
